package com.sams.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageInfo;
import com.sams.entity.School;
import com.sams.entity.Student;
import com.sams.entity.User;
import com.sams.service.BaseInfoService;
import com.sams.service.DataTotalService;
import com.sams.service.SchoolService;
import com.sams.service.StudentService;
import com.sams.util.POIUtil;

@RequestMapping("/student")
@Controller
public class StudentController {

	@Autowired
	private StudentService service;
	@Autowired
	private BaseInfoService baseInfoService;
	@Autowired
	private DataTotalService dataTotalService;
	@Autowired
	private SchoolService schoolService;
	 
	@RequestMapping("/list")
	public String listStu(Integer currentPage,
			Model model, String name,String idcard,Integer schid,Integer zid,String x,
			HttpServletRequest request, HttpSession session) {
		if(currentPage==null) {
			currentPage=1;
		}
		// 以前存 list  和  page对象 ，现在存 分页框架的pageInfo
		// PageInfo 相当于  以前的Page 
		User user =  (User)request.getSession().getAttribute("user");
		if(user==null) {
			model.addAttribute("error", "会话过期，请重新登录");
			return "error";
		}
		//分页查询时，条件的来源 
		if(x!=null) {// 说明是分页信息
			//从session中获取条件
			name=(String)session.getAttribute("name");
			idcard=(String)session.getAttribute("idcard");
			schid=(Integer)session.getAttribute("schid");
			zid=(Integer)session.getAttribute("zid");
		}
		
		
		
		//查询所有的乡镇
		if(user.getRoleid()==1 ||user.getRoleid()==2) {
			 //查询所有镇id
			model.addAttribute("xzList", baseInfoService.findById(user.getZid()));
		}else { 
			 model.addAttribute("xzList", dataTotalService.selectAllZhen());
		}
		 
		PageInfo<Student> pageInfo = service.listStu(currentPage,name,idcard,schid,user,zid);
		model.addAttribute("pageInfo", pageInfo);
		session.setAttribute("name", name);
		session.setAttribute("idcard", idcard);
		session.setAttribute("schid", schid);
		session.setAttribute("zid", zid);
		//如果已选zid ，则需要回显它对应的学校，方便继续选择其他学校
		if(zid!=null && !zid.toString().equals("0")) {
			model.addAttribute("schoolListByZid",schoolService.selectSchoolByZid(zid));
		}
		
		return "student";
	}
	
	@RequestMapping("/findById")
	public Student findById(Integer id) {
		return  service.findById(id);
	}
	/**
	 * 删除
	 * @param id
	 * @return
	 */
	@RequestMapping("/delete")
	public String delete(Integer id) {
		service.delete(id);

		return "forward:/student/list";
	}
	/**
	 * 添加
	 * @param stu
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/add")
	public String add(Student stu,HttpServletRequest request,Model model) {
		User user =  (User)request.getSession().getAttribute("user");
		if(user==null) {
			model.addAttribute("error", "会话过期，请重新登录");
			return "error";
		}
		stu.setUid(user.getId());
		try {
			int count = service.add(stu);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			model.addAttribute("error",e.getMessage());
			return "error";
		}
 		return "redirect:list";
	}
	/**
	 * 更新
	 * @param stu
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/update")
	public String update(Student stu,HttpServletRequest request,Model model) {
		User user =  (User)request.getSession().getAttribute("user");
		if(user==null) {
			model.addAttribute("error", "会话过期，请重新登录");
			return "error";
		}
		stu.setUid(user.getId());
		try {
			service.update(stu);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			model.addAttribute("error",e.getMessage());
			return "error";
		}
		return "redirect:list";
	}
	
	@RequestMapping("/downTemplate")
	public String downTemplate(HttpServletRequest request, HttpServletResponse response) {
		 // 1: 找到excel文件
        String storePath = request.getSession().getServletContext().getRealPath("/") + "template/student/";
        String fileName = "在校学生批量导入.xlsx";

        File file = new File(storePath + fileName);
        if (!file.exists()) {
            throw new RuntimeException("file do not exist");
        }
        InputStream inputStream = null;
        ServletOutputStream servletOutputStream = null;
        // 重置response
        response.reset();
        //设置http头信息的内容
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/vnd.ms-excel");
        response.addHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
        int fileLength = (int) file.length();
        response.setContentLength(fileLength);

        try {
            if (fileLength != 0) {
                inputStream = new FileInputStream(file);
                byte[] buf = new byte[4096];
                // 创建输出流
                servletOutputStream = response.getOutputStream();
                int readLength;
                // 读取文件内容并输出到response的输出流中
                while ((readLength = inputStream.read(buf)) != -1) {
                    servletOutputStream.write(buf, 0, readLength);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("download file error");
        } finally {
            try {
                // 关闭ServletOutputStream
                if (servletOutputStream != null) {
                    servletOutputStream.flush();
                    servletOutputStream.close();
                }
                // 关闭InputStream
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
 
	}
	/**
	 * excel批量导入
	 * @return
	 */
	@RequestMapping("/importBetch")
	public String ExcelInport(@RequestParam("file") MultipartFile file,HttpServletRequest request,Model model) {
		// 1.获取前端表单上传的文件，获取文件名getOriginalFilename()，判断是否是Excel文件
		String fileName = file.getOriginalFilename();
		System.out.println(fileName);
		// * 2.1不是Excel文件，直接返回提示信息
		if (!(fileName.contains("xls") || fileName.contains("xlsx"))) {
			// 格式错误
			model.addAttribute("error", "上传的文件格式不对");
			return "error";
		}
 
		// * 2.2是Excel文件，由于浏览器不能显示文件的绝对路径，所以将文件上传保存在本地的另一个位置
		// * 3.创建上传目录 realpath="D:/uploadExcel"（如果目录不存在）
		String realpath = request.getSession().getServletContext().getRealPath("/");
		System.out.println(realpath);
		// * 2.2是Excel文件，由于浏览器不能显示文件的绝对路径，所以将文件上传保存在本地的另一个位置
		// * 3.创建上传目录 realpath="D:/uploadExcel"（如果目录不存在）
		//String realpath = "D:/uploadExcel";
		File targetDir = new File(realpath+"/uploadExcel");
		if (!targetDir.exists()) {
			targetDir.mkdirs();
			System.out.println("不存在目录");
		}
		// * 4.将上传文件保存在上传目录中new File(realpath,fileName)
		File targetFile = new File(realpath+"/uploadExcel", fileName);
		try {
			file.transferTo(targetFile);
		} catch (Exception e) {
			// 导入错误
			model.addAttribute("error", "文件上传失败");
			 return "error";
		}
		
		User user =  (User)request.getSession().getAttribute("user");
		if(user==null) {
			model.addAttribute("error", "会话过期，请重新登录");
			return "error";
		}
		// // 2: 解析excel数据
        List<String[]> excelData;
		try {
			excelData = POIUtil.readExcel(file);
		} catch (IOException e1) {
			model.addAttribute("error", e1.getMessage());
		     return "error";
		}

	     //批量插入
        try {
	        List<Student> stuList = new ArrayList<Student>();
	        for(String[] arr : excelData) {
	        	Student stu = new Student();
	        	stu.setName(arr[0].trim());
	        	if(stu.getName()==null || "".equals(stu.getName())) {
	        		break;  //如果学生姓名没有填，则不再往下读取
	        	}
	        	if(arr[1]!=null && arr[1].trim().length()!=18) {
	        		throw new Exception(arr[0].trim()+"的身份证号码必须18位");
	        	}
	        	stu.setIdcard(arr[1].trim());// 身份证号   验证必须18位
	        	stu.setStucode(arr[2].trim());//学籍号
	        	stu.setTerm(arr[3].trim());//学期
	        	stu.setLevel(arr[4].trim());//年级
	        	stu.setClasses(arr[5].trim());//班级
	        	stu.setIslodge(arr[6].trim());
	        	stu.setSchoolName(arr[7].trim());
	        	stu.setXueduan(arr[8].trim());
	        	stu.setUid(user.getId());
	        	stuList.add(stu);
	        }
        	boolean flag  = service.insertBatch(stuList);
        	//成功
        	return "forward:/student/list";
        }catch (Exception e) {
        	e.printStackTrace();
        	model.addAttribute("error", e.getMessage());
		     return "error";
		}finally {
			//删除服务器上的文件
			//删除服务器上的文件
			boolean flag=targetFile.delete();
			 System.out.println("===========删除标记："+flag);
		}
	}
	/**
	 * 删除
	 * @param id
	 * @return
	 */
	@RequestMapping("/deleteBatch")
	public String deleteBatch(String ids,Model model) {
		service.deleteBatch(ids);
		model.addAttribute("successFlag", "true");
		return "forward:/student/list";
	}
}
